<template>
  <q-toolbar class="toolbar">
    <!--    <q-btn v-show="showMenuStore.showBtn" flat dense round @click="toggleLeftDrawer" aria-label="Menu" icon="menu"-->
    <!--           class="q-mr-sm"/>-->

    <!--    &lt;!&ndash;        <q-btn size="12px" style="margin-left: 40px;min-width:80px;" @click="goBackToHome" color="primary" label="项目" />&ndash;&gt;-->
    <!--    &lt;!&ndash;        <q-btn size="12px" v-if="isAdmin" style="margin: 0 20px 0 20px;min-width:80px;" color="primary" label="系统" @click="switchSystem" />&ndash;&gt;-->
    <!--&lt;!&ndash;    v-if="showMenuStore.projectManage"&ndash;&gt;-->
    <!--    <q-space/>-->
    <div style="position: relative" v-show="showMenuStore.showBtn" @click.stop="toggleLeftDrawer">
      <q-btn round dense flat color="grey-8" style="position: relative;z-index:100"></q-btn>
      <el-image src="/svgs/MenuShrinkButton.svg" style="width: 25px;position: absolute;top: 3px;right: 4px;z-index:10"
                fit/>
    </div>
    <el-select v-if="showMenuStore.projectManage" v-model="projectValue" placeholder="Select" class="projectChange">
      <el-option
        v-for="item in projectLists"
        :key="item.id"
        :label="item.title"
        :value="item.id"
        @click="goBackPage(item.id)"
      />
    </el-select>
    <!--    <el-input style="width: 55%" size="large" placeholder="Search" :prefix-icon="Search" spellcheck="false"></el-input>-->

    <q-space/>

    <div class="q-gutter-sm row items-center no-wrap">
      <el-image src="/svgs/quickGetStart.svg" style="width: 25px;margin-right: 13px" fit/>
      <el-image src="/svgs/feedback.svg" style="width: 25px;margin-right: 13px" fit/>
      <div style="position: relative">
        <q-btn round dense flat color="grey-8" @click="openFileUploadModal" style="position: relative;z-index:100">
          <q-tooltip>上传列表</q-tooltip>
        </q-btn>
        <el-image src="/svgs/documentation.svg" style="width: 25px;position: absolute;top: 3px;right: 4px;z-index:10" fit/>
      </div>

      <el-dropdown>
        <div style="position: relative">
          <q-btn round dense flat color="grey-8" style="position: relative;z-index:100">
            <q-badge color="red" text-color="white" floating :class="{'apply-shake': shakeTaxtName}">{{ noReadDataNumbers }}</q-badge>
<!--            <q-tooltip>消息通知</q-tooltip>  @click="dialogOpen"  shakeTaxtName-->
          </q-btn>
          <el-image src="/svgs/smallBell.svg" style="width: 25px;position: absolute;top: 3px;right: 4px;z-index:10" fit />
        </div>
        <template #dropdown>
          <el-card class="box-card messages">
            <div class="hasMessage" v-if="noReadDataNumbers > 0">
              <ul class="messageWrapList">
                <li class="items"  v-for="(item, index) in visibleItems" :key="index" @click="toMessageNotification">
                  <div style="position: relative;">
                    <div style="position: relative">
                      <div style="display: inline-block;font-size: 14px;">可跳转的消息通知</div>
                      <div style="display: inline-block;position: absolute;top:2px;margin-left: 5px;width: 8px;height: 8px;border-radius: 50%;background-color: #FF5656"></div>
                    </div>
                    <div style="font-size: 12px;margin-top: 5px;color: #666">我是一条消息通知我是一条消息通知</div>
                  </div>
                </li>
              </ul>
              <div class="getMoreMessage">
                <div style="text-align: center;margin: 0 auto;padding: 10px 0"  @click="toMessageNotification">
                  <span style="color: #666">{{ $t('seeAll') }} ></span>
                </div>
              </div>
            </div>
            <div class="noMeaasge" v-if="noReadDataNumbers === 0">
              <el-image src="/svgs/messageNoticeIcon.svg" style="width: 100px" fit />
              <div>暂无消息通知</div>
            </div>
          </el-card>
        </template>
      </el-dropdown>

      <el-dropdown>
        <el-avatar :size="26" src="https://cdn.quasar.dev/img/avatar2.jpg"/>
        <template #dropdown>
          <el-card class="box-card" style="padding: 10px;width: 150px">
            <div style="display: flex;height: 40px;align-items: center;margin-bottom: 20px">
              <el-avatar :size="40" src="https://cdn.quasar.dev/img/avatar2.jpg"/>
              <div
                :title="UserInfoName"
                style="
                margin-left: 10px;
                font-size: 18px;
                width: 50px;
                cursor: pointer;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              ">
                {{ UserInfoName }}
              </div>
            </div>
            <div style="height: 1px;width: 100%;background-color: #E8E8E8;"></div>
            <div style="display: flex;align-items: center;flex-direction: column">
              <div style="display: flex;height: 22px;align-items: center;margin: 16px 0">
                <el-image src="/svgs/login-people.svg" style="width: 16px;margin-top: 2px" fit/>
                <div style="margin-left: 4px">{{ $t('personalCenter') }}</div>
              </div>
              <div style="display: flex;height: 22px;align-items: center;margin-bottom: 16px;cursor: pointer">
                <el-image src="/svgs/login-clock.svg" style="width: 16px;margin-top: 2px" fit />
                <div style="margin-left: 4px" @click="toMessageNotification">{{ $t('notify') }}</div>
              </div>
            </div>
            <div style="height: 1px;width: 100%;background-color: #E8E8E8;"></div>
            <div style="display: flex;align-items: center;flex-direction: column;cursor: pointer" @click="logout">
              <div style="display: flex;height: 22px;align-items: center;margin-top: 16px">
                <el-image src="/svgs/login-exit.svg" style="width: 16px;margin-top: 2px" fit/>
                <div style="margin-left: 4px">{{ $t('LogOut') }}</div>
              </div>
            </div>
          </el-card>
        </template>
      </el-dropdown>
    </div>
    <el-drawer
      ref="drawerRef"
      v-model="dialog"
      :modal="false"
      title="消息列表"
      :before-close="handleClose"
      direction="rtl"
      class="demo-drawer"
      style="margin-bottom: 0"
      v-loading="loading"
    >
      <div class="demo-drawer__content">
        <div style="display: flex;justify-content: flex-end;width: 100%;margin-bottom: 10px">
          <el-button :type="'warning'" @click="BatchReading" :disabled="noReadDataNumbers === 0">全部已读</el-button>
        </div>
        <ul style="height: 450px;overflow: auto">
          <li class="messageList" v-for="(item,index) in tableDate.results" :key="item.id">
            <h6 style="margin-bottom: 5px">消息{{ index + 1 }}</h6>
            <div class="messageList_content">
              <div>
                <div>{{ item.content_brief }}</div>
                <div style="margin-top: 5px">{{ item.subject }}</div>
              </div>
              <div class="messageList_right">
                <div>{{ item.datetime_received }}</div>
                <el-button
                  round
                  size="small"
                  :type="!item.is_read?'warning':'success'"
                  @click="messageRead(item.id)"
                  style="width: 50px;margin-left: 80px;margin-top: 5px"
                  :disabled="item.is_read"
                  plain
                >{{ !item.is_read ? '未读' : '已读' }}
                </el-button>
              </div>
            </div>
          </li>
        </ul>
        <div class="row" style="justify-content: flex-end;" v-if="tableDate.results.length>0">
          <el-pagination
            v-if="tableDate.results.length>0"
            background layout="total, prev, pager, next"
            :total="tableDate.count"
            @current-change="changePage"
            style="position: absolute;right: 50px;margin-top: 20px;"
          />
        </div>
      </div>
    </el-drawer>
  </q-toolbar>
</template>
<script setup lang="ts">

import {useRouter} from 'vue-router'
import {useMenuStore} from 'src/stores/menu';

const showMenuStore = useMenuStore()
import {useUserStore} from "stores/user";
import {ElMessage} from "element-plus";

const showUserStore = useUserStore()
const platformUploadStore = usePlatformUploadStore()
import {reactive, ref, watch} from "vue";
import {getMessageList, readOver, messageReadOne, isMemberInterface} from 'src/api/user'
import {usePlatformUploadStore} from "stores/platform-upload";

import {dataSetStore} from "stores/dataSet";
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id

let projectLists = ref([]);
let projectValue = ref('')

watch(()=>useMenuStore().currentProject,(newValue,oldValue)=>{
  let dataList:any = JSON.parse(JSON.stringify(newValue));
  projectLists.value = dataList.children;
  projectValue.value = dataList.current.title;
});
pageInit();

function pageInit() {
  if (JSON.stringify(useMenuStore().currentProject) !== '{}') {
    projectLists.value = useMenuStore().currentProject.children;
    projectValue.value = useMenuStore().currentProject.current ? useMenuStore().currentProject.current.title : '';
  }
};

function goBackPage(id: number) {
  isMember(id);
}

function openFileUploadModal() {
  platformUploadStore.openUploadModal()
}

function isMember(id) {
  isMemberInterface(id).then(res => {
    const menuList = JSON.parse(JSON.stringify(showMenuStore.allMenuList));
    const current = menuList.filter((item: any) => item.id === id);//当前项目
    const removeCurrntProject = menuList.filter((item: any) => item.id !== id);//除了当前项目外全部的其他项目
    let obj = {
      label: current[0].title,
      currentProject: true,
      name: 'model',
      current: current[0],
      children: removeCurrntProject,
    };
    // dataSetStore().setMenuOpen(2);
    showMenuStore.replaceCurrentMenuItem(obj)
    showMenuStore.setCurrentProject(obj);
    let userInfo = JSON.parse(localStorage.getItem('user'))
    userInfo['status'] = res.data.status;
    localStorage.setItem('user', JSON.stringify(userInfo))
    router.push({name: 'project-detail', params: {project_id: id}})
  }).catch((error) => {
    console.log('error', error);
    ElMessage.error('获取项目创建人或管理员接口报错！')
  })
}

//项目列表

const projectList: any = []

let noReadDataNumbers = ref(0);
let tableDate = reactive({
  count: 0,
  next: null,
  previous: null,
  results: []
});
let visibleItems = ref(null);
function toMessageNotification(){
  router.push({ name: 'message-notification', params: { project_id: projectId } })
}
const pageData = ref({
  page: 1
})
let shakeTaxtName = ref(false);



const isAdmin = JSON.parse(localStorage.getItem('user') || "{}")['is_admin'];//判断用户是否系统普通用户还是超级管理员
function logout() {
  localStorage.clear()
  router.replace({path: '/v2/login'})
}

const UserInfoName = localStorage.getItem('username')

function toggleLeftDrawer() {
  showMenuStore.showMenu = !showMenuStore.showMenu
}

const switchSystem = () => {
  showMenuStore.replaceMenuItems();
  router.push({name: 'system-user'})
}
const goBackToHome = () => {
  // showMenuStore.restoreMenuItems();
  router.push({path: '/v2'});
}

showUserStore.addObserver(webSocketConnect);
getMessageData(false);
const dialog = ref(false)

const loading = ref(false)

function handleClose() {
  dialog.value = false;
}

const changePage = (currentPage: any) => {
  pageData.value.page = currentPage
  webSocketConnect('消息通知');
}

function dialogOpen() {
  dialog.value = true;
}

function webSocketConnect(message: string) {
  if (message) {
    getMessageData(true);
  }
}

function getMessageData(BooleanValue: boolean) {
  if (BooleanValue) {
    loading.value = true;
  }
  getMessageList({page: pageData.value.page}).then(res => {
    tableDate = res.data;
    noReadDataNumbers.value = res.data.results.filter((re: any) => {
      if (re.is_read) {
        return false
      } else {
        return true
      }
    }).length;
    if (noReadDataNumbers.value > 4) {
      visibleItems.value = res.data.results.slice(0, 4);
    } else if (noReadDataNumbers.value > 0) {
      visibleItems.value = res.data.results.slice(0, noReadDataNumbers.value);
    } else {
      visibleItems.value = [];
    }
    if (noReadDataNumbers.value) {
      shakeTaxtName.value = true
    } else {
      shakeTaxtName.value = false
    }
    if (BooleanValue) {
      loading.value = false;
    }
  })
}

function messageRead(id: number) {
  messageReadOne(id).then(res => {
    getMessageData(true);
  })
}

function BatchReading() {
  readOver({page: pageData.value.page}).then(res => {
    getMessageData(true);
  })
}
</script>
<style scoped lang="scss">

.projectChange {
  position: absolute;
  left: 58px;
  width: 164px;

  ::v-deep .el-input__wrapper {
    box-shadow: none !important;
    background: #f3f4f8 !important;
  }
}

.messages{
  width: 260px;
  cursor: pointer;
  .hasMessage{
    .messageWrapList{
      padding: 10px;
      margin: 0;
      .items{
        margin-top: 10px;
        border-bottom: 1px solid #e8e8e8;
        padding-bottom: 10px
      }
      .items:first-child {
        margin-top: 0;
      }
      .items:last-child:first-child {
        border: none;
        padding-bottom: 0
      }
    }
    .getMoreMessage{
      border-top: 1px solid #e8e8e8;
    }
  }
  .noMeaasge{
    padding: 20px 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}

:deep(.el-card__body){
  padding: 0!important;
}

.toolbar {
  height: 64px;
}

::v-deep .block {
  line-height: 18px;
}

::v-deep .el-drawer__header {
  margin-bottom: 0;
}

li {
  list-style: none
}

.messageList {
  margin-bottom: 20px;
}

.messageList_content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  //margin-bottom: 10px;
  list-style: none;

  .messageList_right {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
  }
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

.apply-shake {
  animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both infinite;
}

::v-deep .el-button--success span {
  color: red !important;
}
</style>
